<?php

namespace app\forms\item;

use yii\db\Exception;
use app\forms\Model;
use app\models\Item;
use app\models\User;
use yii\web\HttpException;
use app\validators\PositiveInteger;

class RemoveUserForm extends Model
{
    public $id;
    public $userId;

    public function rules()
    {
        return [
            ['id', PositiveInteger::class],
            ['id', 'required'],
            ['id', 'exist', 'targetClass' => Item::class, 'targetAttribute' => 'id'],

            ['userId', 'required'],
            ['userId', 'checkArr'],
        ];
    }

    public function checkArr($attribute, $params)
    {
        if (!is_array($this->userId) || empty($this->userId))
            $this->addError($attribute, 'User Id Error');
        foreach ($this->userId as $roleId) {
            if (!is_numeric($roleId) || $roleId <= 0)
                $this->addError($attribute, 'User Id Error');
        }
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function removeUser($param)
    {
        $form = new self;
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $attr = $form->getAttributes();
            (new User())->removeByItem($attr);
        } catch (Exception $e) {
            $form->serverError();
        }
        $form->deleteOk();
    }
}